// 物理常量
const PHYSICS = {
    BASE_MASS: 60, // kg
    ARM_MASS: 5, // kg
    BODY_RADIUS: 0.3, // m
    ARM_LENGTH: 0.8, // m
    GRAVITY: 9.8 // m/s²
};

// 模拟状态
let simulation = {
    isRunning: false,
    time: 0,
    angularMomentum: 0,
    momentOfInertia: 0,
    angularVelocity: 0,
    angle: 0,
    armExtension: 100,
    massDistribution: 5,
    initialOmega: 2,
    dataHistory: []
};

// Canvas 元素
const canvas = document.getElementById('simulationCanvas');
const ctx = canvas.getContext('2d');
const dataCanvas = document.getElementById('dataChart');
const dataCtx = dataCanvas.getContext('2d');

// 控件元素
const initialOmegaSlider = document.getElementById('initialOmega');
const armExtensionSlider = document.getElementById('armExtension');
const massDistributionSlider = document.getElementById('massDistribution');

// 显示元素
const angularMomentumDisplay = document.getElementById('angularMomentum');
const momentOfInertiaDisplay = document.getElementById('momentOfInertia');
const angularVelocityDisplay = document.getElementById('angularVelocity');
const conservationValueDisplay = document.getElementById('conservationValue');

// 初始化
function init() {
    updateDisplayValues();
    setupEventListeners();
    drawSkater();
    drawDataChart();
}

// 设置事件监听器
function setupEventListeners() {
    initialOmegaSlider.addEventListener('input', (e) => {
        simulation.initialOmega = parseFloat(e.target.value);
        document.getElementById('initialOmegaValue').textContent = simulation.initialOmega.toFixed(1);
        if (!simulation.isRunning) {
            resetSimulation();
        }
    });

    armExtensionSlider.addEventListener('input', (e) => {
        simulation.armExtension = parseInt(e.target.value);
        document.getElementById('armExtensionValue').textContent = simulation.armExtension + '%';
        if (!simulation.isRunning) {
            updatePhysics();
            drawSkater();
        }
    });

    massDistributionSlider.addEventListener('input', (e) => {
        simulation.massDistribution = parseFloat(e.target.value);
        document.getElementById('massDistributionValue').textContent = simulation.massDistribution.toFixed(1);
        if (!simulation.isRunning) {
            updatePhysics();
            drawSkater();
        }
    });
}

// 计算转动惯量
function calculateMomentOfInertia() {
    const armExtensionFactor = simulation.armExtension / 100;
    const massDistFactor = simulation.massDistribution / 5;
    
    // 身体转动惯量
    const bodyInertia = 0.5 * PHYSICS.BASE_MASS * PHYSICS.BODY_RADIUS * PHYSICS.BODY_RADIUS;
    
    // 手臂转动惯量（随伸展程度变化）
    const armDistance = PHYSICS.ARM_LENGTH * armExtensionFactor;
    const armInertia = 2 * PHYSICS.ARM_MASS * armDistance * armDistance;
    
    // 总转动惯量
    return (bodyInertia + armInertia) * massDistFactor;
}

// 更新物理量
function updatePhysics() {
    simulation.momentOfInertia = calculateMomentOfInertia();
    
    if (!simulation.isRunning) {
        simulation.angularVelocity = simulation.initialOmega;
    }
    
    // 角动量守恒：L = I * ω = 常数
    if (simulation.angularMomentum === 0) {
        simulation.angularMomentum = simulation.momentOfInertia * simulation.angularVelocity;
    } else {
        // 根据角动量守恒计算新的角速度
        simulation.angularVelocity = simulation.angularMomentum / simulation.momentOfInertia;
    }
    
    updateDisplayValues();
}

// 更新显示值
function updateDisplayValues() {
    angularMomentumDisplay.textContent = simulation.angularMomentum.toFixed(2);
    momentOfInertiaDisplay.textContent = simulation.momentOfInertia.toFixed(2);
    angularVelocityDisplay.textContent = simulation.angularVelocity.toFixed(2);
    conservationValueDisplay.textContent = simulation.angularMomentum.toFixed(2);
}

// 绘制滑冰运动员
function drawSkater() {
    const centerX = canvas.width / 2;
    const centerY = canvas.height / 2;
    const scale = 100; // 缩放因子
    
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    
    // 绘制背景圆圈
    ctx.strokeStyle = '#e9ecef';
    ctx.lineWidth = 2;
    ctx.beginPath();
    ctx.arc(centerX, centerY, 150, 0, 2 * Math.PI);
    ctx.stroke();
    
    // 保存当前状态
    ctx.save();
    ctx.translate(centerX, centerY);
    ctx.rotate(simulation.angle);
    
    // 绘制身体
    ctx.fillStyle = '#667eea';
    ctx.beginPath();
    ctx.ellipse(0, 0, 30, 50, 0, 0, 2 * Math.PI);
    ctx.fill();
    
    // 绘制头部
    ctx.fillStyle = '#764ba2';
    ctx.beginPath();
    ctx.arc(0, -70, 20, 0, 2 * Math.PI);
    ctx.fill();
    
    // 绘制手臂
    const armExtensionFactor = simulation.armExtension / 100;
    const armLength = 80 * armExtensionFactor;
    
    ctx.strokeStyle = '#667eea';
    ctx.lineWidth = 15;
    
    // 左臂
    ctx.beginPath();
    ctx.moveTo(-20, -20);
    ctx.lineTo(-armLength, -armLength * 0.5);
    ctx.stroke();
    
    // 右臂
    ctx.beginPath();
    ctx.moveTo(20, -20);
    ctx.lineTo(armLength, -armLength * 0.5);
    ctx.stroke();
    
    // 绘制腿部
    ctx.strokeStyle = '#667eea';
    ctx.lineWidth = 20;
    
    // 左腿
    ctx.beginPath();
    ctx.moveTo(-15, 50);
    ctx.lineTo(-30, 120);
    ctx.stroke();
    
    // 右腿
    ctx.beginPath();
    ctx.moveTo(15, 50);
    ctx.lineTo(30, 120);
    ctx.stroke();
    
    // 恢复状态
    ctx.restore();
    
    // 绘制角速度指示器
    if (simulation.isRunning) {
        const speed = Math.abs(simulation.angularVelocity);
        const indicatorLength = Math.min(speed * 20, 100);
        
        ctx.strokeStyle = '#28a745';
        ctx.lineWidth = 3;
        ctx.beginPath();
        ctx.arc(centerX, centerY, 160, 0, indicatorLength / 100 * 2 * Math.PI);
        ctx.stroke();
        
        // 绘制箭头
        const arrowAngle = indicatorLength / 100 * 2 * Math.PI;
        const arrowX = centerX + 160 * Math.cos(arrowAngle);
        const arrowY = centerY + 160 * Math.sin(arrowAngle);
        
        ctx.fillStyle = '#28a745';
        ctx.beginPath();
        ctx.moveTo(arrowX, arrowY);
        ctx.lineTo(arrowX - 10 * Math.cos(arrowAngle - 0.3), 
                   arrowY - 10 * Math.sin(arrowAngle - 0.3));
        ctx.lineTo(arrowX - 10 * Math.cos(arrowAngle + 0.3), 
                   arrowY - 10 * Math.sin(arrowAngle + 0.3));
        ctx.closePath();
        ctx.fill();
    }
}

// 绘制数据图表
function drawDataChart() {
    const width = dataCanvas.width;
    const height = dataCanvas.height;
    const padding = 40;
    
    dataCtx.clearRect(0, 0, width, height);
    
    // 绘制坐标轴
    dataCtx.strokeStyle = '#333';
    dataCtx.lineWidth = 2;
    
    // X轴
    dataCtx.beginPath();
    dataCtx.moveTo(padding, height - padding);
    dataCtx.lineTo(width - padding, height - padding);
    dataCtx.stroke();
    
    // Y轴
    dataCtx.beginPath();
    dataCtx.moveTo(padding, padding);
    dataCtx.lineTo(padding, height - padding);
    dataCtx.stroke();
    
    // 绘制标签
    dataCtx.fillStyle = '#333';
    dataCtx.font = '12px Arial';
    dataCtx.textAlign = 'center';
    dataCtx.fillText('时间', width / 2, height - 10);
    
    dataCtx.save();
    dataCtx.translate(15, height / 2);
    dataCtx.rotate(-Math.PI / 2);
    dataCtx.fillText('数值', 0, 0);
    dataCtx.restore();
    
    // 绘制图例
    const legendY = 20;
    const legendX = width - 150;
    
    dataCtx.font = '10px Arial';
    
    // 角动量
    dataCtx.strokeStyle = '#667eea';
    dataCtx.lineWidth = 2;
    dataCtx.beginPath();
    dataCtx.moveTo(legendX, legendY);
    dataCtx.lineTo(legendX + 20, legendY);
    dataCtx.stroke();
    dataCtx.fillStyle = '#667eea';
    dataCtx.textAlign = 'left';
    dataCtx.fillText('角动量 L', legendX + 25, legendY + 4);
    
    // 转动惯量
    dataCtx.strokeStyle = '#764ba2';
    dataCtx.beginPath();
    dataCtx.moveTo(legendX, legendY + 15);
    dataCtx.lineTo(legendX + 20, legendY + 15);
    dataCtx.stroke();
    dataCtx.fillStyle = '#764ba2';
    dataCtx.fillText('转动惯量 I', legendX + 25, legendY + 19);
    
    // 角速度
    dataCtx.strokeStyle = '#28a745';
    dataCtx.beginPath();
    dataCtx.moveTo(legendX, legendY + 30);
    dataCtx.lineTo(legendX + 20, legendY + 30);
    dataCtx.stroke();
    dataCtx.fillStyle = '#28a745';
    dataCtx.fillText('角速度 ω', legendX + 25, legendY + 34);
    
    // 绘制数据
    if (simulation.dataHistory.length > 1) {
        const maxTime = Math.max(...simulation.dataHistory.map(d => d.time));
        const maxL = Math.max(...simulation.dataHistory.map(d => d.angularMomentum));
        const maxI = Math.max(...simulation.dataHistory.map(d => d.momentOfInertia));
        const maxOmega = Math.max(...simulation.dataHistory.map(d => d.angularVelocity));
        const maxValue = Math.max(maxL, maxI, maxOmega);
        
        // 绘制数据线
        const scaleX = (width - 2 * padding) / Math.max(maxTime, 10);
        const scaleY = (height - 2 * padding) / maxValue;
        
        // 角动量
        dataCtx.strokeStyle = '#667eea';
        dataCtx.lineWidth = 2;
        dataCtx.beginPath();
        simulation.dataHistory.forEach((data, index) => {
            const x = padding + data.time * scaleX;
            const y = height - padding - data.angularMomentum * scaleY;
            if (index === 0) {
                dataCtx.moveTo(x, y);
            } else {
                dataCtx.lineTo(x, y);
            }
        });
        dataCtx.stroke();
        
        // 转动惯量
        dataCtx.strokeStyle = '#764ba2';
        dataCtx.beginPath();
        simulation.dataHistory.forEach((data, index) => {
            const x = padding + data.time * scaleX;
            const y = height - padding - data.momentOfInertia * scaleY;
            if (index === 0) {
                dataCtx.moveTo(x, y);
            } else {
                dataCtx.lineTo(x, y);
            }
        });
        dataCtx.stroke();
        
        // 角速度
        dataCtx.strokeStyle = '#28a745';
        dataCtx.beginPath();
        simulation.dataHistory.forEach((data, index) => {
            const x = padding + data.time * scaleX;
            const y = height - padding - data.angularVelocity * scaleY;
            if (index === 0) {
                dataCtx.moveTo(x, y);
            } else {
                dataCtx.lineTo(x, y);
            }
        });
        dataCtx.stroke();
    }
}

// 动画循环
function animate() {
    if (!simulation.isRunning) return;
    
    simulation.time += 0.1;
    simulation.angle += simulation.angularVelocity * 0.1;
    
    // 记录数据
    simulation.dataHistory.push({
        time: simulation.time,
        angularMomentum: simulation.angularMomentum,
        momentOfInertia: simulation.momentOfInertia,
        angularVelocity: simulation.angularVelocity
    });
    
    // 限制数据点数量
    if (simulation.dataHistory.length > 100) {
        simulation.dataHistory.shift();
    }
    
    updatePhysics();
    drawSkater();
    drawDataChart();
    
    requestAnimationFrame(animate);
}

// 开始模拟
function startSimulation() {
    if (simulation.isRunning) return;
    
    simulation.isRunning = true;
    updatePhysics();
    animate();
}

// 重置模拟
function resetSimulation() {
    simulation.isRunning = false;
    simulation.time = 0;
    simulation.angle = 0;
    simulation.angularMomentum = 0;
    simulation.dataHistory = [];
    
    updatePhysics();
    drawSkater();
    drawDataChart();
}

// 启动应用
init();